use std::{fs::File, io::{BufRead, BufReader}, path::Path, sync::{Arc, Mutex}, time::Duration};

use lazy_static::lazy_static;

use crate::{utils::file_dir::makesure_dir, warn};

use super::cluster::CLUSTER;

lazy_static! {
	pub static ref CONFIG_PATH: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref DATA_PATH: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref TOKEN: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref SERVER_URL: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
	pub static ref VERSION: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
}

pub fn init_config() -> Duration {
	let config_path = CONFIG_PATH.lock().unwrap();
	let config_path = config_path.as_str();
	let config_path = Path::new(config_path);

	let config_dir = config_path.parent().unwrap().to_str().unwrap();
	makesure_dir(&config_dir.to_string());

	let file = File::open(config_path).unwrap();
	let reader = BufReader::new(file);

	// 默认更新周期 30s
	let mut duration: u64 = 30;

	for line in reader.lines() {
		let content = line.unwrap();
		let mut content_without_spaces = content.clone();
		content_without_spaces.retain(|c| c != ' ');

		// 忽略空行
		if content_without_spaces.len() == 0 {
			continue;
		}

		// 判断 TOKEN = ***
		if content_without_spaces.starts_with("TOKEN=") {
			let mut token = TOKEN.lock().unwrap();
			*token =
				content_without_spaces["TOKEN=".len()..content_without_spaces.len()].to_string();
			continue;
		}

		// 判断 CLUSTER = ***
		if content_without_spaces.starts_with("CLUSTER=") {
			let first_eq = content_without_spaces.find("=").unwrap();
			let cluster_name = &content_without_spaces[first_eq+1..content_without_spaces.len()];
			CLUSTER.lock().unwrap().name.clear();
			CLUSTER.lock().unwrap().name.push_str(cluster_name);
			continue;
		}

		// 判断更新周期 DURATION = ***
		if content_without_spaces.starts_with("DURATION=") {
			let first_eq = content_without_spaces.find("=").unwrap();
			let duration_str = &content_without_spaces[first_eq+1..content_without_spaces.len()];
			duration = duration_str.parse::<u64>().unwrap();
			continue;
		}

		// 判断 SERVER_URL = ***
		if content_without_spaces.starts_with("SERVER_URL=") {
			let first_eq = content_without_spaces.find("=").unwrap();
			let server_url = &content_without_spaces[first_eq+1..content_without_spaces.len()];
			SERVER_URL.lock().unwrap().clear();
			SERVER_URL.lock().unwrap().push_str(server_url);
			continue;
		}

		// 若不是以上所有情况，那就是配置文件路径
		CLUSTER.lock().unwrap().files.push(content);
	}

	if TOKEN.lock().unwrap().len() == 0 {
		warn!("TOKEN is empty. Make sure your internet env is credible.");
	}

	return Duration::from_secs(duration);
}
